package com.example.firstdemo.ui.screens.pages.mine

import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import androidx.navigation.NavGraphBuilder
import androidx.navigation.NavOptionsBuilder
import androidx.navigation.compose.composable
import com.example.firstdemo.network.service.AuthManager
import com.example.firstdemo.ui.screens.pages.login.navigateToLogin
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.serialization.Serializable

@Serializable
object Mine

fun NavController.navigateToMine(builder: NavOptionsBuilder.() -> Unit = {}) {
    navigate(Mine, builder)
}

fun NavGraphBuilder.mineDestination(
    padding: PaddingValues = PaddingValues(0.dp),
    navController: NavController
) {
    composable<Mine>(
        enterTransition = { fadeIn() },
        exitTransition = { fadeOut() },
        popEnterTransition = { fadeIn() },
        popExitTransition = { fadeOut() }
    ) {
        val viewModel: MineViewModel = viewModel()
        val uiState = viewModel.uiState.collectAsStateWithLifecycle().value

        MineScreen(padding, uiState, {
            CoroutineScope(Dispatchers.IO).launch {
                AuthManager.logout()
                withContext(Dispatchers.Main) {
                    navController.navigateToLogin {
                        popUpTo(0)
                    }
                }
            }
        }) { state -> viewModel.setShowDialog(state) }
    }
}